﻿using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PipeSockets
{
    public class FixedHeaderProtocolParser : IProtocolParser
    {
        private readonly int _headerLength;

        public FixedHeaderProtocolParser(int headerLength)
        {
            _headerLength = headerLength;
        }

        public bool Decode(ReadOnlySequence<byte> buffer, out ReadOnlySequence<byte> message, out long bytesRead)
        {
            message = default;
            // 确保有足够的数据来读取头部
            if (buffer.Length < _headerLength)
            {
                bytesRead = 0;
                return false;
            }

            // 读取头部信息
            var header = buffer.Slice(0, _headerLength);

            // 根据头部信息计算消息体的长度
            // 这里假设头部的最后4个字节表示消息体的长度
            int bodyLength = BitConverter.ToInt32(header.ToArray()[^4..], 0);

            // 确保有足够的数据来读取整个消息
            if (buffer.Length < _headerLength + bodyLength)
            {
                bytesRead = 0;
                return false;
            }

            // 读取消息体
            message = buffer.Slice(_headerLength, bodyLength);
            bytesRead = _headerLength + bodyLength;
            return true;
        }

        public Memory<byte> Encode(byte[] payload)
        {
            var buffer = new byte[_headerLength + payload.Length];
            BinaryPrimitives.WriteInt32LittleEndian(buffer, payload.Length);
            Buffer.BlockCopy(payload, 0, buffer, _headerLength, payload.Length);
            return new Memory<byte>(buffer, 0, buffer.Length);
        }
    }
}
